<?php

require_once 'support.php';

define('ROOT', dirname(__FILE__));
define('DS', DIRECTORY_SEPARATOR);
define('WWW', dirname($_SERVER['PHP_SELF']) . '/');
define('SMARTY_DIR', ROOT . DS . 'libs' . DS . 'Smarty' . DS);
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
define('CONFIG_DATABASE_FILE', 'configs/database.php');

set_include_path(implode(PATH_SEPARATOR, array(
    realpath('libs'),
    get_include_path()
)));
require_once SMARTY_DIR . 'Smarty.class.php';
require_once 'Zend/Loader/Autoloader.php';

$loader = Zend_Loader_Autoloader::getInstance();
$loader->registerNamespace('Mithos');

try {
    Zend_Session::start();

    $config = new Zend_Config(require 'configs/settings.php');
    $database = new Zend_Config(require CONFIG_DATABASE_FILE);

    if (!$config->debug) {
        error_reporting(0);
        ini_set('display_errors', 0);
    }
    
    Mithos_Connection::connect($database->db->toArray());

    ob_start();

    $page = isset($_GET['do']) ? strip_tags(trim($_GET['do'])) : '';
    $regex = '/(http|www|.php|.asp|.net|.gif|.jpg|.html|.htm)/i';

    $template = new Mithos_Template($config->template);
    $template->assign('config', $config->toArray());

    require_once 'pages/template.php';

    if (empty($page) || preg_match($regex, $page) || !file_exists('pages/' . $page . '.php')) {
        $page = 'home';
    }

    require_once 'pages/' . $page . '.php';

    if (!isset($_GET['render']) || $_GET['render'] == 1) {
        $template->display($page . '.html');

        if (!isset($_GET['template']) || $_GET['template'] == 1) {
            $content = ob_get_clean();

            $template->assign('content', $content);
            $template->display('template.html');
        }
    }

    ob_end_flush();
} catch (Exception $e) {
    echo $e->getMessage();
}

?>